#ifndef __LUA_WRAPPER_H__
#define __LUA_WRAPPER_H__

#include "script/scriptmgr.h"

template <class TObject>
class Wrapper
{
public:
	static const char * GetObjectType()
	{
		return SetObjectType();
	}
	static const char * SetObjectType(const char * szObjType = NULL)
	{
		static const char * s_szObjType;
		if (szObjType)
		{
			s_szObjType = szObjType;
		}
		return s_szObjType;
	}
};

template <class TWrapper, class TObject>
class LuaWrapper
{
public:
	LuaWrapper(const char * szMetaName)
	{
		Wrapper<TObject*>::SetObjectType(szMetaName);

		lua_State* luaState = LuaEx::GetInstance().GetLuaState();
		
		if (luaL_newmetatable(luaState, szMetaName) == 0)
		{
			lua_pop(luaState, 1);
			return;
		}

		lua_pushstring(luaState, "__index");
		lua_pushvalue(luaState, -2);
		lua_settable(luaState, -3);

		int classid = luaL_ref(luaState, LUA_REGISTRYINDEX);

		TWrapper::InitWrapper(classid);

		luaL_unref(luaState, LUA_REGISTRYINDEX, classid);
	}
};

#define INIT_WRAPPER(TWrapper, TObject, name)\
	namespace{\
		static LuaWrapper<TWrapper, TObject> s_meta(name);\
	}

#endif